﻿#include "sql_operator.h"




bool QSqlTableModel_My::SetAllFilter(QString &key_str)
{//功能：全表检索
    if(key_str == "")
    {
        this->setFilter( "" );
        //this->select();
        return true;

    }
    QString Filter_str;
    int column;
    int columnCount = this->columnCount();
    //qDebug("列数为%d",columnCount);
    for(column=0; column < columnCount; column++)
    {
        //qDebug("正在组建第%d列的过滤器",column);
        QString Column_name_str = this->record().fieldName(column);
        QString single_column_filter = QString(" %1 LIKE '%%2%' ").arg(Column_name_str).arg(key_str);// "name='lucy'"
        Filter_str += (column!=0?"OR":"") + single_column_filter;
    }
    //qDebug()<<"全文过滤器为:"<<Filter_str;

    //model->setFilter( QString("did = '%1' ").arg(key_str) + QString(" OR name = '%1' ").arg(key_str));
    this->setFilter( Filter_str );
    //this->select();
    return true;
}

bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("meter.db");
    if (!db.open())
    {
        QMessageBox::critical(0, "Cannot open database",
            "Unable to establish a database connection.\n"
                     "This example needs SQLite support. Please read "
                     "the Qt SQL driver documentation for information how "
                     "to build it.\n\n"
                     "Click Cancel to exit.", QMessageBox::Cancel);
        qDebug()<<"打开数据库文件->失败";
        return false;
    }
    else
        qDebug()<<"打开数据库文件->成功";

    QSqlQuery query(db);//关联到db，QSqlQuery可以对db执行sql语句

    //从sqlite的内置表sqlite_master中读出所有的表名
    if (!query.exec("SELECT name,type FROM sqlite_master WHERE type='table' order by name"))
    {
        qDebug()<<"列出数据库中所有的表->失败:"<<query.lastError();
        return false;
    }
    else
    {
        qDebug()<<"列出数据库中所有的表->成功:";

        while(query.next())
        {
            qDebug()<<query.value(0).toString()<<" "//name
                    <<query.value(1).toString();//type
        }

    }

    if (!query.exec("CREATE TABLE table_645_did"))
    {
        qDebug()<<"创建表-失败，原因是："<<query.lastError();
        qDebug()<<"表早已存在，程序继续";
    }
    else
        qDebug()<<"创建表-成功";

    //query.exec("insert into TableDid values(1, 'Danny', 15)");//插入数据
//    query.exec("insert into student values(2, 'Danny2', 16)");//插入数据
    //db.close();
    return true;
}


